<?php 
//all the class/function includes are managed in the includer file
include("include/includer.php");
//page specific includes
//RSS Feed Parser
require_once('magpierss72/rss_fetch.inc');

//get all the configuration variables (custom function in newzbook.php include)
getConfigVars();

//get the sabnzbd categories
$url = $config_sabnzbd_url.'api?mode=get_cats&output=json&apikey='.$config_sabnzbd_apikey;
$categories = file_get_contents($url);
$categories = json_decode($categories, true);
$categories = $categories['categories'];
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<HEAD>
    <?php standardHead("SABnzbd"); ?>
	<link type="text/css" href="style/smoothness/jquery-ui-1.7.2.custom.css" rel="stylesheet" />	
	<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
	<script type="text/javascript" src="js/jquery-ui-1.7.2.custom.min.js"></script>
	<style type="text/css">
		.ui-progressbar-value { background-image: url(images/progress_ani_blue.gif); }
		.ui-progressbar { height:20px; }
		 #queue, #history { list-style-type: none; margin: 0; padding: 0; display:block;} 
		 #queue li, #history li { margin-bottom:5px; }
		 .nzbreport{ background-color:white; }
	</style>
	<script type="text/javascript">
	$(function() {
		$("#queue").sortable();
		$("#queue").disableSelection();
	});
	</script>
</HEAD>

<BODY>
<?php internetSecurity(); ?>
<div style="visibility:hidden;display:none;" id="progress"><div id="progress_bg"></div><a name="loading" /><div id="progress_box"><img id="progress_image" style="padding-left:5px;padding-top:5px;" src="images/ajax-loader.gif" alt="loading...">Your request is being processed...</div></div>
<div class="headercontent">
  <?php headerContent(); ?>
</div>
<div class="maincontent">
<?php
if(!is_dir($config_NZBDropPath)) {
  echo "<div class='warningmessage'>The NZB Drop Path directory does not appear to exist. Check your <a href='configuration.php'>configuration</a></div>";
}
?>
  <div class="block">
    <h2>SABnzbd+</h2>
	<?php 
	//check the PHP version -- 5.2.0 has native decoding of JSON
	//I really didn't want to include another class just for JSON decoding
	//SABnzbd users should be able to get the latest version of PHP
	if (version_compare(PHP_VERSION, '5.2.0') >= 0) {
		//echo 'I am at least PHP version 5.2.0, my version: ' . PHP_VERSION . "\n";
	}
	else {
		echo "NewzBook requires JSON decoding to work with SABnzbd+. PHP version 5.2.0 and newer includes this by default. Otherwise, you can install a <a href='http://www.php.net/manual/en/json.installation.php'>PECL extension</a> on older versions of PHP.";
		exit("</div></body></html>");
	}
	
	/*-----------------------------*\
	 |    SAB Status Information   |
	\*-----------------------------*/
	
	//Build the URL to get the QUEUE (and other info)
	$url = $config_sabnzbd_url."api?mode=queue&output=json&apikey=".$config_sabnzbd_apikey."&ma_username=".$config_sabnzbd_uname."&ma_password=".$config_sabnzbd_pass;
	
	//get the contents of the URL (json string) and json decode it
	$contents = file_get_contents($url);
	$contents = json_decode($contents, true);
	//setup a few variables to use at the end
	$sab_last_warning = $contents['queue']['last_warning'];
	$sab_version = $contents['queue']['version'];
	$sab_loadavg = $contents['queue']['loadavg'];
	//use the array items from the json decoded object to create a basic status display
	echo "<span id='sizeleft'>".$contents['queue']['sizeleft']."</span>/<span id='size'>".$contents['queue']['size']."</span> remaining @ <span id='speed'>".$contents['queue']['speed']."</span>/sec | ETA: <span id='eta'>".$contents['queue']['eta']."</span> (<span id='timeleft'>".$contents['queue']['timeleft']."</span>)";
	echo "<br />";
	echo "<strong>Speed Limit:</strong> <input type='text' id='speedlimit' style='width:50px;' value='".$contents['queue']['speedlimit']."' /><img src='images/accept.png' id='speedlimit_success' style='display:none;'/><br />";
	echo "<a id='pause'>";
	if($contents['queue']['paused']){ echo "Resume"; } else { echo "Pause"; }
	echo "</a><br />";
	echo "<a id='pgrefresh'>Refresh Page</a>";
	echo "<span id='responsemessage' class='warningmessage' style='display:none;'></span><a id='responsemessage_hide' style='border-bottom:1px dotted red;display:none;font-size:80%;'>Clear</a>";
	?>
	<script>
	$(function() {
		/*-------------------------*\
		 |  Display Error Messages |
		\*-------------------------*/
		//display error messages when they occur
		$('#responsemessage').ajaxError(function() {
		  $(this).text('Your request was not successfully processed.');
		  $(this).show();
		  $('#responsemessage_hide').show(); 
		});	
		//enable a hide box for the ajax errors
		$('#responsemessage_hide').click(function() { $('#responsemessage').hide(); $('#responsemessage_hide').hide(); });
		
		/*-------------------------*\
		 |  Periodic Refresh: Main |
		\*-------------------------*/
		//create the function to get the new data and merge it into the DOM
		function refreshmain(){
			//create the url
			var refreshurl = 'sabnzbdhelper.php?mode=refreshmain';
			//send the command
			$.ajax({
			  dataType: 'json',
			  url: refreshurl,
			  success: function(data) {
				//merge the response into the DOM
				//overall summary items
				$('#speed').html(data.queue.speed);
				$('#sizeleft').html(data.queue.sizeleft);
				$('#size').html(data.queue.size);
				$('#eta').html(data.queue.eta);
				$('#timeleft').html(data.queue.timeleft);
				//loop through each queue item and update it
				for ( var i in data.queue.slots ){
					//first check to see if the item exists -- if it does update, if not create it
					if ($('#'+data.queue.slots[i].nzo_id).length>0) {
						//Update the item
						$('#'+data.queue.slots[i].nzo_id+' .item_sizeleft').html(data.queue.slots[i].sizeleft);
						$('#'+data.queue.slots[i].nzo_id+' .item_size').html(data.queue.slots[i].size);
						$('#'+data.queue.slots[i].nzo_id+' .item_eta').html(data.queue.slots[i].eta);
						$('#'+data.queue.slots[i].nzo_id+' .item_timeleft').html(data.queue.slots[i].timeleft);
						//the the percentage is 0, disable the progress bar if it is somehow onscreen
						if(data.queue.slots[i].percentage != 0){
							//check to see if it's instantiated
							if($('#progressbar'+data.queue.slots[i].nzo_id).progressbar("option", "value") == undefined){
								//if it's not created, instantiate the progressbar
								$('#progressbar'+data.queue.slots[i].nzo_id).progressbar({ value: data.queue.slots[i].percentage });
							}else{
								//otherwise, just update it
								$('#progressbar'+data.queue.slots[i].nzo_id).progressbar("option", "value", data.queue.slots[i].percentage );
							}
						}else{ 
							//if the percentage is 0, we really don't even need a progressbar onscreen
							$('#progressbar'+data.queue.slots[i].nzo_id).progressbar( "destroy" );
						}
					}else{
						//The item doesn't exist in the DOM, let's create it
						//build the html (as hidden)
						var itemHTML = "<li style='display:hidden;'><div class='nzbreport' id='"+data.queue.slots[i].nzo_id+"'><span class='reporttitle'>"+data.queue.slots[i].filename+"</span><span class='reporttitle_smaller'>"+data.queue.slots[i].status+"<a class='icon_pause></a><a class='icon_delete'></a></span><br /><span class='remaining'><strong>Remaining:</strong> <span class='item_sizeleft'>"+data.queue.slots[i].sizeleft+"</span>/<span class='item_size'>"+data.queue.slots[i].size+"</span></span><span class='category' style='float:right;'><select><option SELECTED>None</option><option>anime</option><option>apps</option><option>books</option><option>consoles</option><option>emulation</option><option>games</option><option>misc</option><option>movies</option><option>music</option><option>pda</option><option>resources</option><option>tv</option><option>unknown</option><option>xxx</option></select></span><br /><span class='eta'><strong>ETA:</strong> <span class='item_eta'>"+data.queue.slots[i].eta+"</span></span> <span class='timeleft'>(<span class='item_timeleft'>"+data.queue.slots[i].timeleft+"</span>)</span><br /><div id='progressbar"+data.queue.slots[i].nzo_id+"'></div></div></li>";
			
						//create the item (hidden)
						$('#queue').append(itemHTML); 
						
						//show the item
						$('#'+data.queue.slots[i].nzo_id).parent().show('blind',1000);
						
						//instantiate the progress bar if necessary
						if(data.queue.slots[i].percentage != 0){
							$("#progressbar"+data.queue.slots[i].nzo_id).progressbar({ value: data.queue.slots[i].percentage });
						}
					}
					
				}
				//At this point, we should check to see if there are any items on the page that are no longer in the queue
				//setup the array, then get the list of IDs from the DOM selection
				var IDs = [];
				$("#queue").find(".nzbreport").each(function(){ IDs.push(this.id); });
				
				var txt = '';
				var lsrch = IDs.length;
				//alert('IDs Length: '+lsrch);
				//loop through the IDs seeing if they are in the queue still
				for (  i=0; i < lsrch; i++ ){
					//alert('At first level of loop (i)\ni: '+i+'\nx: '+x);
					for( x=0; x < data.queue.slots.length; x++){
					//alert('At second level of loop (x)\ni: '+i+'\nx: '+x);
						if(IDs[i] == data.queue.slots[x].nzo_id){
							//alert('MATCH!\ni: '+i+'\nx: '+x+'\nID: '+IDs[i]+'\nSlot: '+data.queue.slots[x].nzo_id);
							//we have a match -- remove it from the array
							IDs.splice(i,1);
							//reset the searching variables back to 0 so we will go back through
							x=-1; //have to set x to -1 since it will be incremented right away
							i=0;
							//alert('x: '+x+'\ni: '+i);
						}
						else{
							//if we don't have a match, add it to a different array
							//alert('No match\ni: '+i+'\nx: '+x+'\nID: '+IDs[i]+'\nSlot: '+data.queue.slots[x].nzo_id);
						}
					}
				}
				
				//now that we've removed the matches from the array, let's remove the remaining items from the HTML
				for(var i in IDs){
					//first hide the element for visual appeal, then remove it from the list
					$('li #'+IDs[i]).parent().hide('blind',1000,function(){ $(this).remove(); });
					//$('li #'+IDs[i]).hide('blind',1000); //<-- for testing, just hides 
				}
				
				//$('#responsemessage').html(txt);
				//$('#responsemessage').show(); $('#responsemessage_hide').show();	
			  }
			});
		}
		//$('#pgrefresh').click(function(){refreshmain();});
		//refresh the page every five seconds
		var holdTheInterval = setInterval(refreshmain, 5000);
		/*-------------------------*\
		 |   Item Category Change  |
		\*-------------------------*/
		//pause
		$('.category select').change(function() {		
			//get the ID and category of this item
			var nzoID = $(this).closest("div.nzbreport").attr("id");
			var category = $(this).val();
			
			//create the URL to call
			var categoryURL = 'sabnzbdhelper.php?mode=changecategory&value='+nzoID+'&value2='+category;
			
			//send the command
			$.ajax({
			  url: categoryURL,
			  success: function(data) {
				if(data.trim() == 'ok'){
					//highlight the dropdown as green if we are successful
					$('#'+nzoID+' .category select').effect("highlight", {color: '#339933'}, 3000);
				}
				else{
					//the request was processed by the helper, but unsuccessful
					//highlight red
					$('#'+nzoID+' .category select').effect("highlight", {color: 'red'}, 3000);
					//display error
					$('#responsemessage').html(data);
					$('#responsemessage').show(); $('#responsemessage_hide').show();
				}
			  }
			});
		});
		
		/*-------------------------*\
		 |   Item Delete [Queue]    |
		\*-------------------------*/
		//pause
		$('#queue .icon_delete').click(function() {		
			//get the ID of this item
			var nzoID = $(this).closest("div.nzbreport").attr("id");
			
			//create the URL to call
			var itemDeleteURL = 'sabnzbdhelper.php?mode=deleteitem&value='+nzoID;
			
			//create the URL to call
			//var itemPauseURL = 'sabnzbdhelper.php?mode=resumeitem&value='+nzoID+'&value2='+category
			
			//send the command
			$.ajax({
			  url: itemDeleteURL,
			  success: function(data) {
				if(data.trim() == 'ok'){
					//remove the item if we are successful
					$('li #'+nzoID).parent().hide('blind',1000,function(){ $(this).remove(); });
				}
				else{
					//the request was processed by the helper, but unsuccessful
					
					//display error
					$('#responsemessage').html(data);
					$('#responsemessage').show(); $('#responsemessage_hide').show();
				}
			  }
			});
		});
		
		/*-------------------------*\
		 |  Item Delete [History]  |
		\*-------------------------*/
		//pause
		$('#history .icon_delete').click(function() {		
			//get the ID of this item
			var nzoID = $(this).closest("div.nzbreport").attr("id");
			
			//create the URL to call
			var itemDeleteURL = 'sabnzbdhelper.php?mode=deletehistory&value='+nzoID;
			
			//send the command
			$.ajax({
			  url: itemDeleteURL,
			  success: function(data) {
				if(data.trim() == 'ok'){
					//remove the item if we are successful
					$('li #'+nzoID).parent().hide('blind',1000,function(){ $(this).remove(); });
				}
				else{
					//the request was processed by the helper, but unsuccessful
					
					//display error
					$('#responsemessage').html(data);
					$('#responsemessage').show(); $('#responsemessage_hide').show();
				}
			  }
			});
		});
		
		/*-------------------------*\
		 |    Item Pause/Resume    |
		\*-------------------------*/
		//pause
		$('.itemPauseResume').click(function() {		
			//get the ID of this item
			var nzoID = $(this).closest("div.nzbreport").attr("id");

			//Do we need to pause or resume?
			if($(this).hasClass('icon_pause')){
				var prMethod = 'resume';
			}
			else if($(this).hasClass('icon_play')){
				var prMethod = 'pause';
			}
			
			//create the URL to call
			var itemPauseResumeURL = 'sabnzbdhelper.php?mode='+prMethod+'item&value='+nzoID;
			
			//send the command
			$.ajax({
			  url: itemPauseResumeURL,
			  success: function(data) {
				if(data.trim() == 'ok'){
					if(prMethod == 'resume'){
						//change icon to pause icon (named play)
						$('#'+nzoID+' .icon_pause').addClass('icon_play').removeClass('icon_pause');
						//Change status to downloading
						$('#'+nzoID+' .itemStatus').html('Downloading');
					}
					else if(prMethod == 'pause'){
						//change icon to play icon (named pause)
						$('#'+nzoID+' .icon_play').addClass('icon_pause').removeClass('icon_play');
						//Change status to paused
						$('#'+nzoID+' .itemStatus').html('Paused');
					}
				}
				else{
					//the request was processed by the helper, but unsuccessful
					
					//display error
					$('#responsemessage').html(data);
					$('#responsemessage').show(); $('#responsemessage_hide').show();
				}
			  }
			});
		});
		
		/*-------------------------*\
		 |     Pause Function      |
		\*-------------------------*/
		//pause
		$('#pause').click(function() {		
			if($('#pause').text() == 'Pause'){
				//form pause command
				$(this).html('Resume');
				var pauseurl = 'sabnzbdhelper.php?mode=pause';
			}
			else{
				//form  resume command
				$(this).html('Pause');
				var pauseurl = 'sabnzbdhelper.php?mode=resume';
			}
			//send the command
			$.ajax({
			  url: pauseurl,
			  success: function(data) {
				if(data.trim() == 'ok'){
					//no need to do anything if we get a response of OK
				}
				else{
					//the request was processed by the helper, but unsuccessful
					$('#responsemessage').html(data);
					$('#responsemessage').show(); $('#responsemessage_hide').show();
				}
			  }
			});
		});
		
		/*-------------------------*\
		 |   Speed Limit Setting   |
		\*-------------------------*/
		//Set the speed when enter is pressed in the speed box
		$("#speedlimit").keypress(function (e) {  
			if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {  
				var spdurl = 'sabnzbdhelper.php?mode=setspeed&value='+$("#speedlimit").val();
				$.ajax({
				  url: spdurl,
				  success: function(data) {
					if(data.trim() == 'ok'){
						//temporarily show an ok icon so the user knows it actually worked
						$('#speedlimit_success').show('explode');
						$('#speedlimit_success').animate({opacity: 1.0}, 3000)
						$('#speedlimit_success').hide('explode')
	
					}
					else{
						//the request was processed by the helper, but unsuccessful
						$('#responsemessage').html(data);
						$('#responsemessage').show(); $('#responsemessage_hide').show();
					}
				  }
				});
				return false;  
			} else {  
				return true;  
			}  
		});  
	});  
	</script>
	<?php
	
	//debugging
	/*
	echo "<pre>";
	print_r($contents);
	echo "</pre>";
	*/
	
	/*-----------------------------*\
	 |        Queue Details        |
	\*-----------------------------*/
	echo "<h2>Queue</h2>";
	if($contents['queue']['slots'] != null){
	echo "<ul id='queue'>";
		foreach($contents['queue']['slots'] as $item){
			echo "<li>";
			echo "<div class='nzbreport' id='".$item['nzo_id']."'>";
			echo "<span class='reporttitle'>".$item['filename']."</span>";
			echo "<span class='reporttitle_smaller'><span class='itemStatus'>".$item['status']."</span>";
			if($item['status'] == 'Paused'){
				echo "<a class='icon icon_pause itemPauseResume'></a>";
			}else{
				echo "<a class='icon icon_play itemPauseResume'></a>";
			}
			echo "<a class='icon icon_delete'></a></span>";
			
			echo "<br />";
			echo "<span class='remaining'><strong>Remaining:</strong> <span class='item_sizeleft'>".$item['sizeleft']."</span>/<span class='item_size'>".$item['size']."</span></span>";
			echo "<span class='category' style='float:right;'><select>";
			//build out the category list
			foreach($categories as $category){ 
				//make sure we select the category if it's already defined
				if($category == $item['cat']){
					echo "<option SELECTED>".$category;
				}
				else{
					echo "<option>".$category;
				}
				echo "</option>";
			}	
			echo "</select></span>";
			echo "<br />";
			
			echo "<span class='eta'><strong>ETA:</strong> <span class='item_eta'>".$item['eta']."</span></span> <span class='timeleft'>(<span class='item_timeleft'>".$item['timeleft']."</span>)</span>";
			echo "<br />";
			
			echo "<div id='progressbar".$item['nzo_id']."'></div>";
			//if the percentage is not zero, let's create the progressbar
			if($item['percentage'] != 0){
			?>
			<script>
			$("#progressbar<?php echo $item['nzo_id'] ?>").progressbar({
				value: <?php echo $item['percentage'] ?>
			});
			</script>
			<?php
			}
			echo "</div></li>";
			/*Example:
			*[status] => Downloading
			*[index] => 0
			*[nzo_id] => SABnzbd_nzo_BL5wUd
			*[filename] => Spartacus Blood and Sand - 1x03 - Legends
			
			*[eta] => 17:27 Sat 24 Apr
			*[timeleft] => 0:15:23
			[avg_age] => 77d
			
			[script] => None
			[msgid] => 
			[verbosity] => 
			
			[priority] => Normal
			[cat] => None
			[unpackopts] => 3
			
			*[percentage] => 23
			[mb] => 1624.67
			[mbleft] => 1248.30
			*[size] => 1.59 GB
			*[sizeleft] => 1.22 GB
			*/
		}
		echo "</ul>";
	}
	else{
		echo "Queue is empty";
	}
	/*-----------------------------*\
	 |        SAB History          |
	\*-----------------------------*/
	echo "<h2>History</h2>";
	
	//get the contents of the URL (json string) and json decode it
	$url = $config_sabnzbd_url."api?mode=history&output=json&limit=10&apikey=".$config_sabnzbd_apikey;
	$context = null; //setup the context variable for usage below
	$contents = file_get_contents($url, false, $context);
	$contents = json_decode($contents, true);
	/*
	echo "<pre>";
	print_r($contents);
	echo "</pre>";
	*/
	if($contents['history']['slots'] != null){
	echo "<ul id='history'>\r\n";
		foreach($contents['history']['slots'] as $item){
			echo "<li>\r\n";
			echo "<div class='nzbreport' id='".$item['nzo_id']."'>";
			echo "<span class='reporttitle'>".$item['name']."</span>";
			echo "<span class='reporttitle_smaller'><span class='itemStatus'>".$item['status']."</span>";
			echo "<a class='icon icon_delete'></a></span>";
			
			echo "<br />";
			
			if($item['category'] != null){
				echo "Category: <span class='category'>".$item['category']."</span>";
				echo " | ";
			}
			echo "Size: <span class='size'>".$item['size']."</span>";
			echo "<br />";
			echo "Download Time: <span class='download_time'>".duration($item['download_time'])."</span>";
			echo " | ";
			echo "Post Process Time: <span class='postproc_time'>".duration($item['postproc_time'])."</span>";
			echo "<br />";
			echo "</div></li>\r\n";
		}
		echo "</ul>";
	}
	else{
		echo "History is empty";
	}
	/* Sample Items: 
	[5] => Array (
		[action_line] => 
		[show_details] => True
		[script_log] => 
		[meta] => 
		[fail_message] => 
		[loaded] => 
		[id] => 2
		[size] => 1.53 GB
		[category] => tv
		[pp] => D
		[completeness] => 0
		[script] => None
		[nzb_name] => True Blood S03E03 720p HDTV x264 IMMERSE.nzb
		[download_time] => 1169
		[storage] => /media/762f5413-c63e-4021-905d-d0ccf2b834a1/TV/True Blood S03E03 720p HDTV x264 IMMERSE
		[status] => Completed
		[script_line] => 
		[completed] => 1278190858
		[nzo_id] => SABnzbd_nzo_bxSTXx
		[downloaded] => 1640100329
		[report] => 
		[path] => /True Blood S03E03 720p HDTV x264 IMMERSE
		[postproc_time] => 71
		[name] => True Blood S03E03 720p HDTV x264 IMMERSE
		[url] => 
		[bytes] => 1640100329
		[url_info] => 
		[stage_log] => Array
			(
				[0] => Array
					(
						[name] => Download
						[actions] => Array
							(
								[0] => Downloaded in 19 minutes 29 seconds at an average of 1.34 MB/s
							)

					)

				[1] => Array
					(
						[name] => Repair
						[actions] => Array
							(
								[0] => [true.blood.s03e03.720p.hdtv.x264-immerse.sample] Quick Check OK
								[1] => [true.blood.s03e03.720p.hdtv.x264-immerse] Quick Check OK
							)

					)

				[2] => Array
					(
						[name] => Unpack
						[actions] => Array
							(
								[0] => [true.blood.s03e03.720p.hdtv.x264-immerse] Unpacked 1 files/folders in 1 min 9 seconds
							)

					)

			)

	)
	*/
	/*-----------------------------*\
	 |        SAB Add NZB          |
	\*-----------------------------*/
	
	
	
	/*------------------------*\
	 | OLD METHODS / Attempts |
	\*------------------------*/
	/* Using MagpieRSS (using XML output in URL)
	$rss = fetch_rss($url);
	print_r($rss);
	*/
	
	/* GZIP Compressed
	$zd = gzopen($url, "r"); 
	while($line = gzread($zd, 1024)) { 
	$contents .= $line; 
	} 
	gzclose($zd);
	*/
	//echo "<pre>$contents</pre>";
  echo "</div>";
  //need to make this a real footer
  echo "<strong>Last Warning:</strong> <div class='infomessage'>".$sab_last_warning."</div>";
  echo "<strong>Version:</strong> ".$sab_version;
  echo " | ";
  echo "<strong>LoadAvg:</strong> ".$sab_loadavg;
  ?>
</BODY>